import React, { useContext, useEffect, useState } from "react";
import { Button, Form, Input, Popconfirm, Space, message } from "antd";
import type { TableColumnsType, FormProps } from 'antd';
import dayjs from 'dayjs';
import ClassificationProvider, { ClassContext } from "./store";
import { getClassificationList, deleteClassification } from './../../api/classification';
import TableComponent from '../../components/TableComponent';
import PaginationComponent from '../../components/PaginationComponent';
import AddOrEdit from './AddOrEdit';
import styles from "./index.module.scss";
import type { classificationReqPramesType, classificationPaginationType, classificationResDataType } from "./../../types/classificationType"
import { info } from "console";

const Classification = () => {
    const { state, dispatch } = useContext(ClassContext);
    const [form] = Form.useForm();
    const [paging, setPaging] = useState<classificationPaginationType>({ page: 1, size: 10 });
    // 表格
    const columns: TableColumnsType<classificationResDataType> = [
        {
            title: '分级',
            dataIndex: 'level',
            key: 'level',
        },
        {
            title: '分类名',
            dataIndex: 'categoryName',
            key: 'categoryName',
        },
        {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            render: (_, { createTime }) => {
                return dayjs.unix(createTime).format("YYYY-MM-DD hh:mm:ss")
            }
        },
        {
            title: '更新时间',
            dataIndex: 'updateTime',
            key: 'updateTime',
            render: (_, { updateTime }) => {
                return dayjs.unix(updateTime).format("YYYY-MM-DD hh:mm:ss")
            }
        },
        {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, { categoryId, level, parentCategoryId, sub }) => (
                <Space size="middle">
                    {level === 1 ? (<Button type="link" onClick={() => {
                        dispatch({ type: "SET_DATAITEM", payLoad: { categoryId:undefined, parentCategoryId:categoryId, level:2 } });
                        dispatch({ type: "CHANGE_ADDOREDIT", payLoad: true });
                        dispatch({ type: "CHANGE_TYPE", payLoad: "addSub" });
                    }}>新增</Button>) : null}

                    <Button type="link" onClick={() => {
                        dispatch({ type: "SET_DATAITEM", payLoad: { categoryId, parentCategoryId, level } });
                        dispatch({ type: "CHANGE_ADDOREDIT", payLoad: true });
                        dispatch({ type: "CHANGE_TYPE", payLoad: "editSub" });
                    }}>编辑</Button>
                    <Popconfirm title="确定删除此分类?" onConfirm={() => {
                        if (sub && sub.length > 0) {
                            return message.info("此分类还有子分类未删除，请检查删除后再删除！");
                        }
                        handDeleteClassification(categoryId);

                    }}>
                        <Button type="link">删除</Button>
                    </Popconfirm>

                </Space>
            )
        },
    ];

    // 设置选项内容
    const onFinish: FormProps<classificationReqPramesType>['onFinish'] = (e) => {
        dispatch({ type: "SET_PRAMES", payLoad: e });
    };
    const onReset = () => {
        dispatch({ type: "CLEAR_PRAMES" });
        form.resetFields()
    }
    const getList = () => {
        getClassificationList({ ...state.prames, paging }).then(res => {
            if (res.code === 0) {
                dispatch({ type: "SET_RESDATA", payLoad: res.data })
            }
        })
    }
    // 删除
    const handDeleteClassification = (e: number) => {
        deleteClassification({ categoryId: e }).then(res => {
            if (res.code === 0) {
                getList();
                message.success("删除成功！");
            }
        })
    }

    useEffect(() => {
        getList();
    }, [state.prames, paging])

    return <>
        <div className={styles.Hader}>
            <h2>分类管理</h2>
            <Form
                layout='inline'
                onFinish={onFinish}
                initialValues={state.prames}
                form={form}
            >
                <Form.Item<classificationReqPramesType> name="categoryName" style={{ width: 250 }} label="名称">
                    <Input placeholder="请输入名称" />
                </Form.Item>
                <Form.Item<classificationReqPramesType> name="categoryId" style={{ width: 250 }} label="分类ID">
                    <Input placeholder="请输入分类ID" />
                </Form.Item>
                <Form.Item<classificationReqPramesType> name="parentCategoryId" style={{ width: 250 }} label="上级分类ID">
                    <Input placeholder="上级分类ID" />
                </Form.Item>
                <Form.Item>
                    <Space>
                        <Button type="primary" htmlType='submit'>查询</Button>
                        <Button htmlType="reset" onClick={() => onReset}>
                            重置
                        </Button>
                    </Space>
                </Form.Item>
            </Form>
        </div>
        <TableComponent<classificationResDataType> data={state.data.data} columns={columns}>
            <Button type="primary" onClick={() => {
                dispatch({ type: "SET_DATAITEM", payLoad: { categoryId:undefined, parentCategoryId:0, level:1 } });
                dispatch({ type: "CHANGE_TYPE", payLoad: "addFirst" });
                dispatch({ type: "CHANGE_ADDOREDIT", payLoad: true });
            }}>新增分类</Button>
        </TableComponent>
        <PaginationComponent count={state.data.count} onChange={() => setPaging} />
        <AddOrEdit getList={getList}/>
    </>
}

const LayOut: React.FC = () => {
    return <ClassificationProvider>
        <Classification />
    </ClassificationProvider>
}


export default LayOut;


